using System;
using System.Configuration;
using System.Linq;
using NUnit.Framework;
using TechTalk.SpecFlow;
using WatiN.Core;
using TableRow = WatiN.Core.TableRow;

namespace Isis.UI.Tests
{
    [Binding]
    public class BrowsingSteps
    {
        private Browser _browser;

        [Given(@"I have a browser")]
        public void GivenIHaveABrowser()
        {
            _browser = new IE();
        }

        [When(@"I navigate to /Isis")]
        public void WhenINavigateToIsis()
        {
            var rootUrl = new Uri(ConfigurationManager.AppSettings["RootUrl"]);
            var absoluteUrl = new Uri(rootUrl, "/Isis");
            _browser.GoTo(absoluteUrl);
        }

        [When(@"I click on the (.+) tab")]
        public void WhenIClickOnTheTab(string tabName)
        {
            Link tabLink = _browser.Links.FirstOrDefault(l => l.Text == tabName);

            if (tabLink == null)
            {
                throw new ApplicationException("Test could not find the correct link to click on.");
            }

            tabLink.Click();
        }

        [Then(@"I should be on the (.+) page")]
        public void ThenIShouldBeOnThePage(string tabName)
        {
            string[] titleParts = tabName.Split(' ');
            string title = _browser.Title;

            foreach (string part in titleParts)
            {
                Assert.That(title.Contains(part));
            }

        }

        [Then(@"I should see a list of processes")]
        public void ThenIShouldHaveAListOfProcesses()
        {
            ElementCollection<TableRow> tableRows = _browser.ElementsOfType<TableRow>();

            Assert.IsNotNull(tableRows);
            Assert.IsNotEmpty(tableRows.ToArray());
        }

        [Then(@"I should see the Isis Assembly")]
        public void ThenIShouldSeeTheIsisAssembly()
        {
            ElementCollection<TableCell> tableRows = _browser.ElementsOfType<TableCell>();

            Assert.IsNotNull(tableRows);
            Assert.IsNotEmpty(tableRows.ToArray());

            TableCell isisCell = tableRows.FirstOrDefault(x => x.Text == "Isis");

            Assert.IsNotNull(isisCell);
        }

        [Then(@"I should see the Isis dll")]
        public void ThenIShouldSeeTheIsisDll()
        {
            ElementCollection<TableCell> tableRows = _browser.ElementsOfType<TableCell>();

            Assert.IsNotNull(tableRows);
            Assert.IsNotEmpty(tableRows.ToArray());

            TableCell isisCell = tableRows.FirstOrDefault(x => x.Text == "Isis.dll");

            Assert.IsNotNull(isisCell);
        }



        ~BrowsingSteps()
        {
            IDisposable foo = _browser;
            try
            {
                foo.Dispose();
            }
            catch (Exception exception)
            {
            }
        }
    }
}